#include "KEY.h"
#include "KEYConfig.h"

void KEY_Init(void)
{
    uint8_t i=0;
    GPIO_setMode(GPIO_Port3, GPIO_Pin0 | GPIO_Pin1 | GPIO_Pin2 | GPIO_Pin3, GPIO_Mode_OutPP);
    GPIO_setBit(GPIO_Port3, GPIO_Pin0 | GPIO_Pin1 | GPIO_Pin2 | GPIO_Pin3, 0);
    // PWM0_Init();
    for(i=0; i<keyop_length; i++)
    {
        TK_Init(keyop[i]);
    }
    /*PWM0独立模式*/PWM_Init(PWM0_PRESSEL_FHRC_D8, 1000);
	/*PWM01 独立模式*/PWM_IndependentModeConfigEX(PWM01, lowlight, PWM_OUTPUTSTATE_ENABLE);
	/*PWM05 独立模式*/PWM_IndependentModeConfigEX(PWM05, lowlight, PWM_OUTPUTSTATE_ENABLE);
	/*PWM06 独立模式*/PWM_IndependentModeConfigEX(PWM06, lowlight, PWM_OUTPUTSTATE_ENABLE);
	/*PWM07 独立模式*/PWM_IndependentModeConfigEX(PWM07, lowlight, PWM_OUTPUTSTATE_ENABLE);
	/*PWM0*/PWM_Aligned_Mode_Select(PWM0_Edge_Aligned_Mode);
	/*PWM0*/PWM_FaultDetectionConfigEX(PWM0_Type, DISABLE);
	/*PWM0*/PWM_FaultDetectionModeConfigEX(PWM0_Type, PWM0_Immediate_Mode, PWM0_FaultDetectionVoltage_Low, PWM0_WaveFilteringTime_0us);
	/*PWM0中断使能*/PWM_ITConfigEX(PWM0_Type, DISABLE, LOW);
	/*PWM0开关*/PWM_CmdEX(PWM0_Type, ENABLE);
    TouchKeyInit();
}

/**
 * @brief 扫描按键
 * @return uint8_t 扫描到的按键
 */
uint8_t KEY_Scan()
{
    uint8_t i;
    uint32_t Key_Buf = 0;
    for(i=0; i<4; i++)
    {
        // 灯低亮度
        // 设置占空比 100
        PWM_IndependentModeConfigEX(PWM0x[i], lowlight, PWM_OUTPUTSTATE_ENABLE);
    }
    //开始扫描
    if (SOCAPI_TouchKeyStatus & 0x40)
    {
        SOCAPI_TouchKeyStatus &= 0xbf;
        TouchKeyRestart();
    }
    if (SOCAPI_TouchKeyStatus & 0x80)
    {
        SOCAPI_TouchKeyStatus &= 0x7f;
        Key_Buf = TouchKeyScan();
        TouchKeyRestart();
    }
    //扫描完毕
    //开始按键处理
    for (i = 0; i < 4; i++)
    {
        if (Key_Buf >> keyop[i] == 1)
        {
            // 灯高亮度
            PWM_IndependentModeConfigEX(PWM0x[i], highlight, PWM_OUTPUTSTATE_ENABLE);
            return i;
        }
    }
    return i;
}
